package com.qipay.api.callback.controller.v1;

import com.qipay.baas.model.Order;
import com.qipay.order.service.OrderService;
import com.qipay.sp.SpConfigService;
import com.qipay.utils.MD5Util;
import com.qipay.utils.RequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 万家回调
 */
@RestController
@RequestMapping("/callback/v1/wanjia")
public class WjCallbackController {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
	OrderService orderService;

    @Autowired
	SpConfigService spConfigService;

    @RequestMapping(value = "/wx")
    private String unionCreate(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        Map<String, String> params = RequestUtils.getRequestParams(request);
        logger.info("request from " + request.getRequestURI() + ", request body:" + params);
        String tradeNo = params.get("orderid");
        Order order = orderService.getByTradeNo(tradeNo);
        if(order==null) {
            logger.info("回调失败：查无此订单="+tradeNo);
            return "fail";
        }
        Map<String, Object> keyValues = spConfigService.getKeyValues(order.getSpId());
        String token = keyValues.get("token").toString();
        String key = params.get("key");
        String keyStr =generateStr(params,token);
        String myKey = MD5Util.sign(keyStr,"utf-8").toLowerCase();
        if(key.equals(myKey)){
            order.setSpTradeNo(params.get("platform_trade_no"));
            orderService.update(order);
            orderService.setOrderSuccess(order.getId(), null);
            return "OK";
        }else {
            logger.info("回调失败：签名sign不一致，tradeNo="+tradeNo);
        }
        return "fail";
    }

    public String generateStr(Map<String, String>params ,String token){
        return params.get("orderid")+params.get("orderuid")+params.get("platform_trade_no")
                +params.get("price")+params.get("realprice")+token;
    }

}
